//
//  MPWebViewController.m
//  MobileProject
//
//  Created by caiqilin on 2016/11/15.
//  Copyright © 2016年 caiqilin. All rights reserved.
//

#import "MPWebViewController.h"
#import "SVProgressHUD.h"
#import "WebViewJavascriptBridge.h"
#import "SDWebImageManager.h"
#import "AFNetworking.h"
@interface MPWebViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;

@property (nonatomic, copy)NSString *detailID;
@property (nonatomic, copy)NSMutableString *requestUrlString;
@property (nonatomic, strong)WebViewJavascriptBridge *bridge;
@end

@implementation MPWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    self.title = @"detail";
    //    self.view.backgroundColor = [UIColor greenColor];
    //    self.webView.backgroundColor = [UIColor redColor];
    //    NSString * jsonPath = [[NSBundle mainBundle]pathForResource:@"sanguo" ofType:@"json"];
    //    NSData * jsonData = [[NSData alloc]initWithContentsOfFile:jsonPath];
    //    NSArray *jsonArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    [self initJSbirdge];
    [self requestBanner];
    
    //    [self setupWebViewByData:jsonArr];
    
    
    
    self.webView.scalesPageToFit = YES;
    self.webView.backgroundColor = [Util stringTOColor:@"#ffebd2"];
    //    self.url = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
}

- (void)requestBanner {
    //查找GameScore表
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"webh"];
    NSString *title = @"";
    if(_menuTitle.length > 0){
        title = _menuTitle;
    }else {
    title = [_obj objectForKey:@"title"];

    }
    
    [bquery whereKey:@"title" equalTo:title];
    
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if(array.count >0){
            BmobObject *obj = array[0];
            NSString *href = [obj objectForKey:@"href"];
            if(href.length < 100){
                self.url = [href stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
            }else{
                [self setupWebViewByData:href];
            }
        }else {
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.frame = self.webView.bounds;
            imageView.image = [UIImage imageNamed:@"qidai.jpg"];
            imageView.backgroundColor = [UIColor redColor];
            [self.webView addSubview:imageView];
            self.navigationItem.title = @"敬请期待";
        }
        
    }];
    
}


#pragma mark - 监听点击
- (IBAction)reload {
    [self.webView reload];
}

- (IBAction)back {
    [self.webView goBack];
}

- (IBAction)forward {
    [self.webView goForward];
}

#pragma mark - <UIWebViewDelegate>
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.backItem.enabled = webView.canGoBack;
    self.forwardItem.enabled = webView.canGoForward;
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if(title.length > 0){
        self.navigationItem.title = title;
    }
    [SVProgressHUD dismiss];
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD showWithStatus:@"正在加载中,请稍后"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
}

- (void)initJSbirdge {
    
    [WebViewJavascriptBridge enableLogging];
    
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"ObjC received message from JS: %@", data);
        responseCallback(@"Response for message from ObjC");
    }];
    
    [_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
    }];
}

- (void)setupRequest {
    
    self.detailID = @"AQ72N9QG00051CA1";//一张图片
    self.detailID = @"AQ4RPLHG00964LQ9";//多张图片
    NSMutableString *urlStr = [NSMutableString stringWithString:@"http://c.m.163.com/nc/article/xukunhenwuliao/full.html"];
    [urlStr replaceOccurrencesOfString:@"xukunhenwuliao" withString:_detailID options:NSCaseInsensitiveSearch range:[urlStr rangeOfString:@"xukunhenwuliao"]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self setupWebViewByData:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error == %@",error);
        
    }];
    
}

- (void)setupWebViewByData:(NSString *)data {
    
    if (data.length > 0) {
        NSMutableString *allTitleStr =[NSMutableString stringWithString:@"<p class = 'thicker'>xukun</p>"];
        
        [allTitleStr replaceOccurrencesOfString:@"xukun" withString:data options:NSCaseInsensitiveSearch range:[allTitleStr rangeOfString:@"xukun"]];
        
        NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"webViewHtml" ofType:@"html"];
        NSMutableString* appHtml = [NSMutableString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
        
        NSRange range = [appHtml rangeOfString:@"<p>mainnews</p>"];
        
        [appHtml replaceOccurrencesOfString:@"<p>mainnews</p>" withString:allTitleStr options:NSCaseInsensitiveSearch range:range];
        NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
        [_webView loadHTMLString:appHtml baseURL:baseURL];
        NSString *title = [_obj objectForKey:@"title"];
        if(title.length > 0){
            self.navigationItem.title = title;
        }else if (_menuTitle.length > 0) {
            self.navigationItem.title = _menuTitle;

        }
        
        //        }
    }
    
}


- (NSString *)replaceUrlSpecialString:(NSString *)string {
    
    return [string stringByReplacingOccurrencesOfString:@"/"withString:@"_"];
}


@end

